﻿using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using ESoft.Core.Interceptor;
using Autofac.Extras.DynamicProxy2;
using ESoft.Core.Data.DAO;
using ESoft.Core.Data.DAO.Impl;
using ESoft.Core.Data;
using Edu.Web.Data;
using ESoft.Core.Data.Service.Impl;
using ESoft.Core.Data.Service;

namespace Edu.Web
{
    public class AutoFacBootStrapper
    {
        public static void CoreAutoFacInit()
        {
            var builder = new ContainerBuilder();

            SetupResolveRules(builder);

            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            var container = builder.Build();

            //注册api容器需要使用HttpConfiguration对象
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        private static void SetupResolveRules(ContainerBuilder builder)
        {
            //WebAPI只用引用services和repository的接口，不用引用实现的dll。
            var assmblyArr = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
            builder.RegisterType<TransactionInterceptor>();

            builder.RegisterAssemblyTypes(assmblyArr).Where(t => t.Name.EndsWith("DAO")).AsImplementedInterfaces().InstancePerRequest().EnableInterfaceInterceptors().InterceptedBy(typeof(TransactionInterceptor));

            builder.RegisterAssemblyTypes(assmblyArr)
                .Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerRequest()
                .EnableInterfaceInterceptors().InterceptedBy(typeof(TransactionInterceptor));
            
            // 通用泛型接口注入
            builder.RegisterGeneric(typeof(BaseDAO<,>)).As(typeof(IBaseDAO<,>)).InstancePerRequest();
            builder.RegisterGeneric(typeof(BaseService<,>)).As(typeof(IBaseService<,>)).InstancePerRequest();

            // 连接串配置
            builder.RegisterType<EduContextOption>().As<IDbContextOption>().SingleInstance();
        }
    }
}